<template>
  <div>
    <el-header>
      <i class="el-icon-menu" style="font-size: 1.2vw"> 菜单 管理界面</i>
    </el-header>
    <el-main>
      <el-table
        max-height="100%"
        :data="
          menus.filter(
            (data) =>
              !search || data.name.toLowerCase().includes(search.toLowerCase())
          )
        "
        :header-cell-style="{
          width: '100%',
          color: '#333',
          fontSize: '1vw',
          fontWeight: 600,
          background: 'rgba(236,245,255,1)',
        }"
        :row-style="{
          fontSize: '0.8vw',
          color: 'rgb(85,26,139)',
        }"
        style="width: 100%; border: 1px solid rgba(208, 215, 223, 0.9)"
      >
        <el-table-column align="center" prop="foodId" sortable label="编号">

        </el-table-column>
        <el-table-column align="center" label="图片" prop="picture">
          <template slot-scope="scope">
          <el-image :src="scope.row.picture"></el-image>
        </template>
        </el-table-column>
        <el-table-column align="center" prop="name" sortable label="名称">
        </el-table-column>
        <el-table-column
          align="center"
          prop="price"
          width="150"
          sortable
          label="价格 ￥"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="number"
          sortable
          label="销售量"
        >
        </el-table-column>
        <el-table-column align="center" width="140">
          <!-- eslint-disable-next-line -->
          <template slot="header" slot-scope="scope">
            <el-row>
              <el-col :span="16">
                <el-input
                  v-model="search"
                  prefix-icon="el-icon-search"
                  size="mini"
                  v-focus
                  placeholder="名称"
                />
              </el-col>

              <el-col :span="4"> </el-col>
              <el-col :span="4">
                <el-button
                  size="mini"
                  type="success"
                  icon="el-icon-plus"
                  plain
                  @click="addMenu()"
                >
                </el-button>
              </el-col>
            </el-row>
          </template>

          <template slot-scope="scope">
            <el-row>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                plain
                @click="editMenu(scope.row.foodId)"
              >
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                plain
                @click="deletCar(scope.row.foodId, scope.row.name)"
              ></el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-main>

    <!-- 修改弹窗 -->
    <div v-show="editflag">
      <!-- 外部 -->
      <div class="mask" v-if="showModal" @click="showModal = false"></div>
      <!-- 内容 -->
      <div class="pop" v-if="showModal">
        <div class="title" style="">
          <span @click="editflag = false">修改菜单</span>
        </div>
        <div class="content">
          <el-row> 编号: {{ menu.id }} </el-row><br>
          <el-row>
            <input
              type="file"
              @change="tirggerFile($event)"
              :src="imgUrl"
              v-if="imgUrl"
            /> </el-row
          ><br />
          <el-row style="padding-bottom: 20px">
            <img style="" :src="imgUrlStar" />
          </el-row>
          <br />
          <el-row>
            名称:
            <el-input
              type="text"
              v-model="menu.name"
              placeholder="修改名称"
              v-focus
              style="width: 70%"
            /> </el-row
          ><br />
          <el-row>
            价格:
            <el-input
              type="text"
              style="width: 70%"
              v-model="menu.price"
              placeholder="修改价格"
            />￥
          </el-row>
        </div>
        <el-row class="conSty" style="padding-top: 20px; text-algin: center">
          <el-col :span="12">
            <el-button @click="updateMenu(menu.id)" type="mini">确定</el-button>
          </el-col>
          <el-col :span="12"
            ><el-button
              style="float: right"
              type="mini"
              @click="editflag = false"
              >取消</el-button
            ></el-col
          >
        </el-row>
      </div>
    </div>
    <!-- 新增弹窗 -->
    <div v-show="addflag">
      <!-- 外部 -->
      <div class="mask" v-if="showModal" @click="showModal = false"></div>
      <!-- 内容 -->
      <div class="pop" v-if="showModal">
        <div class="title" style="">
          <span @click="addflag = false">新增菜单</span>
        </div>
        <div class="content">
          <el-row>
            编号:
            <el-input
              type="text"
              v-model="addMenuData.foodId"
              placeholder="编号"
              v-focus
              style="width: 70%"
            />
          </el-row><br>
          
          <el-row> <img :src="picture" v-if="picture" /> </el-row><br />
          <el-row>
            名称:
            <el-input
              type="text"
              v-model="addMenuData.name"
              placeholder="名称"
              v-focus
              style="width: 70%"
            /> </el-row
          ><br />
          <el-row>
            价格:
            <el-input
              type="text"
              style="width: 70%"
              v-model="addMenuData.price"
              placeholder="价格"
            />￥
          </el-row>
        </div>
        <el-row class="conSty" style="padding-top: 20px; text-algin: center">
          <el-col :span="12">
            <el-button @click="addMenuUpdata" type="mini">确定</el-button>
          </el-col>
          <el-col :span="12"
            ><el-button
              style="float: right"
              type="mini"
              @click="addflag = false"
              >取消</el-button
            ></el-col
          >
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import adminMixin from "../../mixin/adminMixin";
export default {
  name: "adminMenu",
  mixins: [adminMixin],
  data() {
    return {
      // picture: require("../../assets/user.jpg"),
      imgUrlStar:"",
      imgUrl: new FormData(),
      search: "",
      imgUrls:[],
      menus: [],
      menu: {
        id: "",
        name: "",
        price: "",
      },
      addMenuData: {
        foodId: 0,
        name: "",
        price: 0.0,
      },
      editflag: false, //修改弹窗
      addflag: false, //新增弹窗
      showModal: false, //弹框显示与隐藏
    };
  },
  mounted() {
    
    this.getMenusData("/admin/queryFoodsList");
  },
  watch: {
    Menus: function () {
      Object.keys(this.Menus.data.data).forEach((key) => {
        this.Menus.data.data[key].picture="http://120.79.136.233:9898/admin/queryFoodsPictureById/"+key
        this.menus.push(this.Menus.data.data[key]);
        this.imgUrls.push({img:"http://120.79.136.233:9898/admin/queryFoodsPictureById/"+key})
      });
    },
  },
  methods: {
    tirggerFile(event) {
      let file = event.target.files[0];
      this.imgUrl.append("file", file);
    },

    editMenu(id) {
      console.log(id);
      this.showModal = true;
      this.editflag = true;
      let element = this.Menus.data.data[id];
      if (id === element.foodId) {
        this.menu.id = element.foodId;
        this.imgUrlStar="http://120.79.136.233:9898/admin/queryFoodsPictureById/" + id
        this.menu.name = element.name;
        this.menu.price = element.price;
              }
    },

    updateMenu(id) {
      this.showModal = false;
      this.editflag = false;
      this.menus.forEach((element) => {
        if (id === element.foodId) {
          element.name = this.menu.name;
          element.price = this.menu.price;
          // 发送修改菜单信息请求
          this.$axios({
            method: "post",
            url: "/admin/UpDateFood",
            data: JSON.stringify(element),
            headers: { "Content-Type": "application/json" },
          })
            .then((res) => {
              this.Menus = res;
            })
            .catch((e) => {
              console.log(e);
            });
        }
      });
      // 向服务器发送修改图片请求
      console.log(this.imgUrl)
      this.$axios({
        method: "post",
        url: "/admin/saveFoodsPicture",
        data: this.imgUrl,
        params: { foodId: id },
        headers: { "Content-Type": "multipart/form-data" },
      })
        .then((res) => {
          alert("图片修改成功");
          this.imgUrlStar =
            "http://120.79.136.233:9898/admin/queryFoodsPictureById/" + id;
          this.imgUrl = res.data;
        })
        .catch((e) => {
          console.log(e);
        });
    },

    toGetImg() {
      if (inputElement === null) {
        // 生成文件上传的控件
        inputElement = document.createElement("input");
        inputElement.setAttribute("type", "file");
        inputElement.style.display = "none";

        if (window.addEventListener) {
          inputElement.addEventListener("change", this.uploadFile, false);
        } else {
          inputElement.attachEvent("onchange", this.uploadFile);
        }

        document.body.appendChild(inputElement);
      }
      inputElement.click();
    },
    uploadFile(el) {
      if (el && el.target && el.target.files && el.target.files.length > 0) {
        console.log(el);
        const files = el.target.files[0];
        const isLt2M = files.size / 1024 / 1024 < 2;
        const size = files.size / 1024 / 1024;
        console.log(size);
        // 判断上传文件的大小
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        } else if (files.type.indexOf("image") === -1) {
          //如果不是图片格式
          // this.$dialog.toast({ mes: '请选择图片文件' });
          this.$message.error("请选择图片文件");
        } else {
          const that = this;
          const reader = new FileReader(); // 创建读取文件对象
          reader.readAsDataURL(el.target.files[0]); // 发起异步请求，读取文件
          reader.onload = function () {
            // 文件读取完成后
            // 读取完成后，将结果赋值给img的src
            that.imgUrl = this.result;
            // console.log(this.result);
            // 数据传到后台
            //const formData = new FormData()
            //formData.append('file', files); // 可以传到后台的数据
          };
        }
      }
    },

    beforeDestroy() {
      if (inputElement) {
        if (window.addEventListener) {
          inputElement.removeEventListener(
            "change",
            this.onGetLocalFile,
            false
          );
        } else {
          inputElement.detachEvent("onchange", this.onGetLocalFile);
        }
        document.body.removeChild(inputElement);
        inputElement = null;
        console.log("========inputelement destroy");
      }

      this.$bus.$off("LoginAdminId");
    },

    addMenu() {
      this.showModal = true;
      this.addflag = true;
    },

    addMenuUpdata() {
      this.showModal = false;
      this.addflag = false;
      // 向服务器发送添加请求
      this.$axios({
        method: "post",
        url: "/admin/AddFood",
        data: JSON.stringify(this.addMenuData),
        headers: { "Content-Type": "application/json" },
      })
        .then((res) => {
          this.Students = res;
        })
        .catch((e) => {
          console.log(e);
        });
    },

    deletCar(id, name) {
      if (confirm("确定删除此菜单: " + name + " ?")) {
        this.menus = this.menus.filter((menu) => menu.id !== id);
        // 发送删除菜单请求
        this.postMenuDelete("/admin/deleteFoodById/", id);
      }
    },
  },
};
</script>

<style scoped>
.el-header {
  height: 3vh !important;
  line-height: 3vh;
  text-align: center;
  background-color: #d0d7df;
  width: 100%;
  margin-bottom: 10px !important;
}

.el-main {
  text-align: center;
  /* background-color: #164070; */
  padding: 0px;
  margin-left: 20%;
  width: 60%;
}

img {
  width: 100px;
  height: 80px;
}

.mask {
  background-color: rgb(71, 93, 98);
  /* 透明度 */
  opacity: 0.5;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.pop {
  top: 50%;
  left: 50%;
  width: 15%;
  height: 55%;
  background-color: white;
  padding-top: 2%;
  padding-left: 4%;
  padding-right: 4%;
  border-radius: 4px;
  transform: translate(-50%, -50%);
  position: fixed;
  color: #fff;
  box-shadow: 3px 3px 4px rgba(0, 0, 0, 0.2);
  z-index: 2;
}

.title {
  color: black !important;
  font-size: 1.4vw !important;
  text-align: center;
  font-weight: 500;
  padding-bottom: 20px !important;
}

.content {
  color: black !important;
  font-size: 1vw;
  width: 100%;
  padding-bottom: 10px;
  border: none;
}
</style>